<template>
  <div class="environment-management">
    <div class="card">
      <div class="card-header flex-between">
        <span>环境列表</span>
        <button @click="showAddModal = true" class="btn">+ 添加环境</button>
      </div>

      <div v-if="loading" class="text-center p-2">
        <div class="loading"></div>
      </div>

      <table v-else>
        <thead>
          <tr>
            <th>环境名称</th>
            <th>环境类型</th>
            <th>描述</th>
            <th>主机数量</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="env in environments" :key="env.id">
            <td>{{ env.name }}</td>
            <td>
              <span class="badge" :class="getEnvBadgeClass(env.env_type)">
                {{ getEnvTypeName(env.env_type) }}
              </span>
            </td>
            <td>{{ env.description || '-' }}</td>
            <td>{{ env.host_count }}</td>
            <td>{{ formatDate(env.created_at) }}</td>
            <td>
              <div class="flex gap-1">
                <button @click="viewHosts(env)" class="btn btn-info" style="padding: 4px 8px; font-size: 10px;" title="查看主机">主机</button>
                <button @click="editEnvironment(env)" class="btn" style="padding: 4px 8px; font-size: 10px;">编辑</button>
                <button @click="deleteEnvironment(env.id)" class="btn btn-danger" style="padding: 4px 8px; font-size: 10px;">删除</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 主机列表弹窗 -->
    <div v-if="showHostsModal" class="modal" @click.self="showHostsModal = false">
      <div class="modal-content modal-lg">
        <div class="modal-header">
          <h2>{{ currentEnv?.name }} - 主机列表</h2>
          <button @click="showHostsModal = false" class="modal-close">✕</button>
        </div>
        <div class="modal-body">
          <div v-if="envHosts.length === 0" class="text-center p-2">
            暂无主机
          </div>
          <table v-else class="hosts-table">
            <thead>
              <tr>
                <th>主机名</th>
                <th>IP地址</th>
                <th>端口</th>
                <th>用户名</th>
                <th>环境类型</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="host in envHosts" :key="host.id">
                <td>{{ host.name }}</td>
                <td>{{ host.ip }}</td>
                <td>{{ host.port }}</td>
                <td>{{ host.username }}</td>
                <td>
                  <span class="badge" :class="getEnvBadgeClass(currentEnv.env_type)">
                    {{ getEnvTypeName(currentEnv.env_type) }}
                  </span>
                </td>
                <td>
                  <button @click="changeHostEnv(host)" class="btn btn-sm" style="padding: 4px 8px; font-size: 10px;">修改环境</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 修改主机环境弹窗 -->
    <div v-if="showChangeEnvModal" class="modal" @click.self="showChangeEnvModal = false">
      <div class="modal-content modal-sm">
        <div class="modal-header">
          <h2>修改主机环境</h2>
          <button @click="showChangeEnvModal = false" class="modal-close">✕</button>
        </div>
        <div class="modal-body">
          <p>主机: <strong>{{ selectedHost?.name }}</strong></p>
          <form @submit.prevent="saveHostEnv">
            <div class="form-group">
              <label>新环境 *</label>
              <select v-model="newHostEnv" required>
                <option value="">请选择环境</option>
                <option v-for="env in environments" :key="env.id" :value="env.id">
                  {{ env.name }} ({{ getEnvTypeName(env.env_type) }})
                </option>
              </select>
            </div>
            <div class="flex gap-1 mt-2">
              <button type="submit" class="btn">保存</button>
              <button type="button" @click="showChangeEnvModal = false" class="btn btn-danger">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Add/Edit Modal -->
    <div v-if="showAddModal || showEditModal" class="modal" @click.self="closeModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>{{ showEditModal ? '编辑环境' : '添加环境' }}</h2>
          <button @click="closeModal" class="modal-close">✕</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveEnvironment">
            <div class="form-group">
              <label>环境名称 *</label>
              <input v-model="formData.name" type="text" required />
            </div>
            <div class="form-group">
              <label>环境类型 *</label>
              <select v-model="formData.env_type" required>
                <option value="">请选择</option>
                <option value="dev">开发环境</option>
                <option value="test">测试环境</option>
                <option value="staging">预发布环境</option>
                <option value="prod">生产环境</option>
              </select>
            </div>
            <div class="form-group">
              <label>环境描述</label>
              <textarea v-model="formData.description" rows="4"></textarea>
            </div>
            <div class="flex gap-1 mt-2">
              <button type="submit" class="btn">保存</button>
              <button type="button" @click="closeModal" class="btn btn-danger">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '../services/api'

const environments = ref([])
const loading = ref(false)
const showAddModal = ref(false)
const showEditModal = ref(false)
const showHostsModal = ref(false)
const showChangeEnvModal = ref(false)
const currentEnv = ref(null)
const envHosts = ref([])
const selectedHost = ref(null)
const newHostEnv = ref('')

const formData = ref({
  name: '',
  env_type: '',
  description: ''
})

onMounted(() => {
  fetchEnvironments()
})

const fetchEnvironments = async () => {
  loading.value = true
  try {
    const response = await api.getEnvironments()
    environments.value = response.results || response
  } catch (error) {
    console.error('Failed to fetch environments:', error)
  } finally {
    loading.value = false
  }
}

const editEnvironment = (env) => {
  formData.value = { ...env }
  showEditModal.value = true
}

const saveEnvironment = async () => {
  try {
    if (showEditModal.value) {
      await api.updateEnvironment(formData.value.id, formData.value)
    } else {
      await api.createEnvironment(formData.value)
    }
    await fetchEnvironments()
    closeModal()
  } catch (error) {
    console.error('Failed to save environment:', error)
    alert('保存失败: ' + (error.response?.data?.detail || error.message))
  }
}

const deleteEnvironment = async (id) => {
  if (!confirm('确定要删除这个环境吗?')) return
  try {
    await api.deleteEnvironment(id)
    await fetchEnvironments()
  } catch (error) {
    console.error('Failed to delete environment:', error)
    alert('删除失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 查看该环境下的主机
const viewHosts = async (env) => {
  currentEnv.value = env
  try {
    const response = await api.getHosts()
    const allHosts = response.results || response
    // 过滤出属于该环境的主机
    envHosts.value = allHosts.filter(host => host.environment === env.id)
    showHostsModal.value = true
  } catch (error) {
    console.error('Failed to fetch hosts:', error)
    alert('获取主机列表失败')
  }
}

// 修改主机环境
const changeHostEnv = (host) => {
  selectedHost.value = host
  newHostEnv.value = currentEnv.value.id
  showChangeEnvModal.value = false
  showChangeEnvModal.value = true
}

// 保存主机新环境
const saveHostEnv = async () => {
  try {
    await api.updateHost(selectedHost.value.id, {
      ...selectedHost.value,
      environment: newHostEnv.value
    })
    alert('主机环境修改成功！')
    showChangeEnvModal.value = false
    // 刷新主机列表
    await viewHosts(currentEnv.value)
    await fetchEnvironments()
  } catch (error) {
    console.error('Failed to update host environment:', error)
    alert('修改失败: ' + (error.response?.data?.detail || error.message))
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  formData.value = { name: '', env_type: '', description: '' }
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const getEnvTypeName = (type) => {
  const typeMap = {
    'dev': '开发',
    'test': '测试',
    'staging': '预发布',
    'prod': '生产'
  }
  return typeMap[type] || type
}

const getEnvBadgeClass = (type) => {
  const classMap = {
    'dev': 'badge-online',
    'test': 'badge-unknown',
    'staging': 'badge-warning',
    'prod': 'badge-offline'
  }
  return classMap[type] || 'badge-unknown'
}
</script>

<style scoped>
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: var(--color-bg-secondary);
  border: 2px solid var(--color-accent-cyan);
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-lg {
  max-width: 900px;
}

.modal-sm {
  max-width: 500px;
}

.btn-info {
  background: linear-gradient(135deg, #2196f3, #42a5f5);
  border-color: #2196f3;
}

.btn-info:hover {
  background: linear-gradient(135deg, #1976d2, #2196f3);
}

.hosts-table {
  width: 100%;
  margin-top: 10px;
}

.hosts-table th,
.hosts-table td {
  padding: 10px;
  text-align: left;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 10px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 2px solid var(--color-border);
}

.modal-header h2 {
  color: var(--color-accent-cyan);
  text-transform: uppercase;
  letter-spacing: 2px;
  font-size: 18px;
}

.modal-close {
  background: transparent;
  border: none;
  color: var(--color-accent-red);
  font-size: 24px;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}

.badge-warning {
  background: rgba(255, 184, 0, 0.2);
  color: var(--color-accent-gold);
  border: 1px solid var(--color-accent-gold);
}
</style>
